#ifndef _THREAD_H_
#define _THREAD_H_

#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <functional>

namespace ThreadModule
{
    static uint32_t number = 1;
    class Thread
    {
        using func_t = std::function<void()>;
    private:
        void EnableDetach()
        {
            std::cout << "线程被分离了" << std::endl;
            _isdetach = true;
        }
    public:
        Thread(func_t func): _tid(0), _isdetach(false), _isrunning(false), _func(func)
        {
            _name = "thread-" + std::to_string(number++);
        }

        void Detach()
        {
            if(_isdetach)
            {
                return;
            }
            if(_isrunning)
            {
                pthread_detach(_tid);//前后都可以
            }
            EnableDetach();
        }

        void EnableRunning()
        {
            _isrunning = true;
        }
        
        //静态成员函数是没有this指针的，所以如果我们想要调用private内部的包装器
        //那我们就需要手动传入this指针去访问包装器
        static void* Routine(void* args)
        {
            //根据当前对象的this指针，在类内访问函数。
            Thread * self = static_cast<Thread*>(args);
            self->_func();
            return nullptr;
        }

        bool Start()
        {
            if(_isrunning)
            {
                return false;
            }
            int n = pthread_create(&_tid, nullptr, Routine, this);
            if(n != 0)
            {
                std::cout << "创建子进程错误" << std::endl;
                return false;
            }
            std::cout << "start success" << std::endl;
            if(_isdetach)
            {
                Detach();
            }
            EnableRunning();
            return true;
        }

        bool Stop()
        {
            if(_isrunning)
            {
                int n = pthread_cancel(_tid);
                if(n  != 0)
                {
                    std::cout << "cancel fault" << std::endl;
                    return false;
                }
                std::cout << "stop success" << std::endl;
            }
            _isrunning = false;
            return true;
        }

        void Join()
        {
            //有没有运行都可以，但是detach需要考虑
            if(_isdetach)
            {
                return;
            }
            int n = pthread_join(_tid, nullptr);
            if(n != 0)
            {
                std::cout << "join false" << std::endl;
                return;
            }
            std::cout << "join success" << std::endl;
        }

        ~Thread()
        {

        }
    private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        func_t _func;
    };
}

#endif